package com.ruiysoft.service.mdse.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruiysoft.controller.integralmdse.InnrIntegralMdseApi;
import com.ruiysoft.controller.integralmdse.vo.InnrIntegralMdseVo;
import com.ruiysoft.entity.feight.Freight;
import com.ruiysoft.entity.mdse.MerchandiseCategory;
import com.ruiysoft.entity.mdse.MerchandisePictureSku;
import com.ruiysoft.entity.mdse.MerchandisePictureSpu;
import com.ruiysoft.entity.mdse.MerchandiseRuleValue;
import com.ruiysoft.entity.mdse.MerchandiseRuleValueRela;
import com.ruiysoft.entity.mdse.MerchandiseSku;
import com.ruiysoft.entity.mdse.MerchandiseSpu;
import com.ruiysoft.entity.supplier.Supplier;
import com.ruiysoft.mapper.mdse.*;
import com.ruiysoft.pub.consts.EnumUtil;
import com.ruiysoft.pub.core.Result;
import com.ruiysoft.pub.entity.PageInfo;
import com.ruiysoft.service.feight.IFreightService;
import com.ruiysoft.service.mdse.IMerchandiseCategoryService;
import com.ruiysoft.service.mdse.IMerchandiseManage;
import com.ruiysoft.service.mdse.IMerchandisePictureSkuService;
import com.ruiysoft.service.mdse.IMerchandisePictureSpuService;
import com.ruiysoft.service.mdse.IMerchandiseRuleValueRelaService;
import com.ruiysoft.service.mdse.IMerchandiseRuleValueService;
import com.ruiysoft.service.mdse.IMerchandiseSkuService;
import com.ruiysoft.service.mdse.IMerchandiseSpuService;
import com.ruiysoft.service.mdse.IMerchandiseStock;
import com.ruiysoft.service.mdse.bean.*;
import com.ruiysoft.service.mdse.consts.MdseEnum;
import com.ruiysoft.service.supplier.SupplierService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class MerchandiseManageImpl implements IMerchandiseManage {
	private Logger logger  = LoggerFactory.getLogger(getClass());
	private final static String SKU_STOCK = "skuStock:";
	@Resource
	RedisTemplate<String,Integer> stockTemplate;
	@Resource
	private IMerchandiseSpuService spuService;

	@Resource
	private InnrIntegralMdseApi innrIntegralMdseApi;
	@Resource
	private IMerchandiseSkuService skuService;
	@Resource
	private IMerchandisePictureSpuService spuPicService;
	@Resource
	private IMerchandisePictureSkuService skuPicService;
	@Resource
	private IMerchandiseCategoryService cateService;
	@Resource
	private IMerchandiseRuleValueRelaService ruleValueRelaService;
	@Resource
	private IMerchandiseRuleValueService ruleValueService;
	@Resource
	private IMerchandiseStock mdseStock;

	@Autowired
	MerchandiseRuleValueRelaMapper merchandiseRuleValueRelaMapper;

	@Autowired
	MerchandiseRuleValueMapper merchandiseRuleValueMapper;

	@Autowired
	MerchandiseSpuMapper merchandiseSpuMapper;

	@Autowired
	MerchandisePictureSpuMapper merchandisePictureSpuMapper;

	@Autowired
	MerchandiseSkuMapper merchandiseSkuMapper;

	@Autowired
	SupplierService supplierService;

	@Autowired
	IFreightService freightService;

	private IPage<MerchandiseSpu> findspuPageByCondition(MerchandiseCondition mdseCondition) throws Exception {
		QueryWrapper<MerchandiseSpu> wrapper = new QueryWrapper<>();

		if(mdseCondition.getCategoryId()!=null){
			wrapper.eq("main_category",mdseCondition.getCategoryId());
		}
		if(mdseCondition.getStatus()!=null){
			wrapper.eq("status",mdseCondition.getStatus());
		}
		if(mdseCondition.getDelFlag()!=null){
			wrapper.eq("del_flag",mdseCondition.getDelFlag());
		}
		if(mdseCondition.getShopId()!=null){
			wrapper.eq("shop_id",mdseCondition.getShopId());
		}
		if(StringUtils.isNotBlank(mdseCondition.getMdseName())){
			wrapper.like("merchandise_name","%"+mdseCondition.getMdseName()+"%");
		}

//		return spuService.page(new Page<>(mdseCondition.getPageIndex(),mdseCondition.getPageSize()),wrapper);

		return spuService.selectLeftJoinMany(mdseCondition.getShopId(), mdseCondition.getCategoryId());
	}

	@Override
	public Integer createOrEditSku(SkuDtail skuDtail) {
		return skuService.createOrEditSku(skuDtail);
	}

	@Override
	public List<SkuDtail> querySkuList(Long shopId, Long spuId) {
		return skuService.querySkuList(shopId, spuId);
	}

	@Override
	public PageInfo<MerchandiseSpuDto> findspuDtoPageByCondition(MerchandiseCondition mdseCondition) throws Exception {
		IPage<MerchandiseSpu> page = findspuPageByCondition(mdseCondition);

		List<MerchandiseSpuDto> spuDtoList = new ArrayList<>();

		page.getRecords().forEach(spu->{
			MerchandiseSpuDto spuDto = new MerchandiseSpuDto();
			spuDto.setSpu(spu);

			//查询sku信息
			List<MerchandiseSkuDto> mdseSkuDtoList = findMdseSkuDtoBySpuId(spu.getSpuId());
			spuDto.setSkuDtoList(mdseSkuDtoList);

			//查询分类
			MerchandiseCategory mdseCategory = cateService.getById(spu.getMainCategory());
			spuDto.setCategory(mdseCategory);

			//查询图片
			MerchandisePictureSpu mdsePicSpu = spuPicService.findMdsePicOneBySpuId(spu.getSpuId());
			List<MerchandisePictureSpu> mdsePicSpuList = new ArrayList<>();
			if(mdsePicSpu!=null){
				mdsePicSpuList.add(mdsePicSpu);
			}
			spuDto.setSpuPicList(mdsePicSpuList);

			// 供应商
			Supplier supplier =  supplierService.getOne(new QueryWrapper<Supplier>().eq("supplier_code", spu.getSupplierCode()), false);
			if(supplier != null)
				spuDto.setSupplier(supplier);

			// 运费
			Freight freight = freightService.getById(spu.getFreightTemplateId());
			if(freight != null)
				spuDto.setFreight(freight);

			spuDtoList.add(spuDto);
		});

		return new PageInfo<>(spuDtoList, (Page) page);
	}

	@Override
	public MerchandiseSpuDto findMdseSpuDtoBySpuId(Long spuId, Long shopId) throws Exception {
		MerchandiseSpu spu = spuService.getById(spuId);
		if(spu!=null&&Objects.equals(spu.getShopId(),shopId)){
			MerchandiseSpuDto spuDto = new MerchandiseSpuDto();
			spuDto.setSpu(spu);
			//查询sku信息
			List<MerchandiseSkuDto> mdseSkuDtoList = findMdseSkuDtoBySpuId(spu.getSpuId());
			spuDto.setSkuDtoList(mdseSkuDtoList);
			//查询分类
			MerchandiseCategory mdseCategory = cateService.getById(spu.getMainCategory());
			spuDto.setCategory(mdseCategory);
			//查询图片
			List<MerchandisePictureSpu> mdsePicSpuList = spuPicService.findMdsePicListBySpuId(spu.getSpuId());
			spuDto.setSpuPicList(mdsePicSpuList);
			//查询相关规格-规格值
			List<MerchandiseRuleValue> ruleValues = ruleValueService.findListBySpuId(spu.getSpuId());
			spuDto.setRuleValues(ruleValues);
			return spuDto;
		}
		return null;
	}

	@Override
	@Transactional
	public void sava(MerchandiseSpuDto merchandiseSpuDto) throws Exception {
		if(merchandiseSpuDto==null||merchandiseSpuDto.getSpu()==null){
			throw  new Exception("没有要保存的信息");
		}
		//保存初始化信息
		merchandiseSpuDto.getSpu().setDelFlag(EnumUtil.DelFlag.NO.getIndex())
				.setStatus(MdseEnum.MdseStatus.DOWN.getIndex())
				.setCreator(merchandiseSpuDto.getSpu().getUpdator())
				.setCreateTime(new Date())
				.setUpdateTime(new Date());
		spuService.saveOrUpdate(merchandiseSpuDto.getSpu());
		//处理图片
		if(merchandiseSpuDto.getSpuPicList()!=null&&!merchandiseSpuDto.getSpuPicList().isEmpty()){
			merchandiseSpuDto.getSpuPicList().stream().filter(Objects::nonNull)
					.forEach(pic->pic.setSpuId(merchandiseSpuDto.getSpu().getSpuId())
							.setShopid(merchandiseSpuDto.getSpu().getShopId()));
			spuPicService.saveOrUpdateBatch(merchandiseSpuDto.getSpuPicList());
		}

		//处理规格-规格值
		Map<String,Long> ruleMap = null;
		if(merchandiseSpuDto.getRuleValues()!=null&&!merchandiseSpuDto.getRuleValues().isEmpty()){
			merchandiseSpuDto.getRuleValues().stream().filter(Objects::nonNull)
					.forEach(ruleValue->ruleValue.setSpuId(merchandiseSpuDto.getSpu().getSpuId())
							.setShopid(merchandiseSpuDto.getSpu().getShopId()));

			ruleValueService.saveOrUpdateBatch(merchandiseSpuDto.getRuleValues());
			ruleMap = merchandiseSpuDto.getRuleValues().stream().filter(Objects::nonNull)
					.collect(Collectors.toMap(rule->rule.getRuleName()+rule.getRuleValue(),MerchandiseRuleValue::getId,(a,b)->a));

		}
		//处理sku
		if(merchandiseSpuDto.getSkuDtoList()!=null&&!merchandiseSpuDto.getSkuDtoList().isEmpty()){
			Map<String, Long> finalRuleMap = ruleMap;
			merchandiseSpuDto.getSkuDtoList().stream()
					.filter(dto->dto!=null&&dto.getSku()!=null)
					//sku信息初始化
					.peek(dto->dto.getSku()
							.setSpuId(merchandiseSpuDto.getSpu().getSpuId())
							.setShopId(merchandiseSpuDto.getSpu().getShopId())
							.setMerchandiseName(merchandiseSpuDto.getSpu().getMerchandiseName())
							.setDelFlag(dto.getSku().getDelFlag()!=null?dto.getSku().getDelFlag():EnumUtil.DelFlag.NO.getIndex())
							.setStatus(MdseEnum.MdseStatus.DOWN.getIndex())
							.setMainCategory(merchandiseSpuDto.getSpu().getMainCategory())
							.setCreator(merchandiseSpuDto.getSpu().getUpdator())
							.setCreateTime(new Date())
							.setUpdator(merchandiseSpuDto.getSpu().getUpdator())
							.setUpdateTime(new Date()))
					.filter(dto->dto.getRuleValues()!=null)
					.forEach(dto->{
						logger.info(JSON.toJSONString(finalRuleMap));
						logger.info(JSON.toJSONString(dto.getRuleValues()));
						if(finalRuleMap!=null&&!finalRuleMap.isEmpty()&&(dto.getRuleValues()==null||dto.getRuleValues().isEmpty())){
							throw new IllegalArgumentException("sku没有关联规格");
						}
						dto.getRuleValues().stream().filter(Objects::nonNull)
							.forEach(ruleValue -> {
								if(finalRuleMap != null){
									//处理新增sku的ruleValue,存上id
									ruleValue.setId(finalRuleMap.get(ruleValue.getRuleName()+ruleValue.getRuleValue()));
								}
							});});
			saveSkuDtos(merchandiseSpuDto.getSkuDtoList());
		}
	}

    @Override
    public MerchandiseSkuDto findMdseSkuDtoBySkuId(Long skuId) throws Exception{
        MerchandiseSku sku = skuService.getById(skuId);
        if(sku!=null){
            MerchandiseSkuDto skuDto = new MerchandiseSkuDto();
            skuDto.setSku(sku)
                    //查询spu信息
                    .setSpu(spuService.getById(sku.getSpuId()))
                    .setSkuPics(skuPicService.findSkuPicListBySkuId(sku.getSkuId()))
                    .setSpuPics(spuPicService.findMdsePicListBySpuId(sku.getSpuId()))
                    .setRuleValues(ruleValueService.findListBySpuId(sku.getSpuId()))
                    .setRuleValueRelas(ruleValueRelaService.list(new QueryWrapper<MerchandiseRuleValueRela>().in("sku_id",findSkuIdBySpuId(sku.getSpuId()))));
            return skuDto;
        }
        return null;
    }

	@Override
	public PageInfo<MerchandiseSkuDto> findSkuDtoPageByCondition(MerchandiseCondition condition) {
		IPage<MerchandiseSku> page = findSkuPageByCondition(condition);

		List<MerchandiseSkuDto> skuDtoList = new ArrayList<>();
		page.getRecords().forEach(sku->{
			MerchandiseSkuDto skuDto = fullSkuDtoBySku(sku);
            skuDtoList.add(skuDto);
		});

		return new PageInfo<MerchandiseSkuDto>(skuDtoList, (Page) page);
	}

    private MerchandiseSkuDto fullSkuDtoBySku(MerchandiseSku sku) {
		MerchandiseCategory cate = cateService.getById(sku.getMainCategory());
        MerchandiseSkuDto skuDto =new MerchandiseSkuDto()
                .setSpu(spuService.getById(sku.getSpuId()))
                .setSkuPics(skuPicService.findSkuPicListBySkuId(sku.getSkuId()))
				.setCateName(cate!=null?cate.getCategoryName():"")
                .setSku(sku);
        //查询图片
        MerchandisePictureSku mdsePicSku = skuPicService.findMdsePicOneBySkuId(sku.getSkuId());
        if(mdsePicSku==null){
			MerchandisePictureSpu mdsePicSpu = spuPicService.findMdsePicOneBySpuId(sku.getSpuId());
			mdsePicSku = new MerchandisePictureSku().setPath(mdsePicSpu.getPath());
		}
		List<MerchandisePictureSku> mdsePicSkuList = new ArrayList<>();
		mdsePicSkuList.add(mdsePicSku);
		skuDto.setSkuPics(mdsePicSkuList);
		//查询规格用于处理商品名
        skuDto.setRuleValues(findRuleValueListBySkuId(sku.getSkuId()));

        return skuDto;
	}

    @Override
	@Transactional
	public void upStatus(Long spuId, Integer status) {
		//更新spu
		spuService.updateById(new MerchandiseSpu().setStatus(status).setSpuId(spuId));
		//更新sku
		skuService.update(new MerchandiseSku().setStatus(status),new UpdateWrapper<MerchandiseSku>().eq("spu_id",spuId));
	}

    @Override
    @Transactional
    public void upAllStatus(List<Long> spuIds, Integer status, Long shopId) {
        //更新spu
        spuService.update(new MerchandiseSpu().setStatus(status),new UpdateWrapper<MerchandiseSpu>().in("spu_id",spuIds).eq("shop_id",shopId));
        //更新sku
        skuService.update(new MerchandiseSku().setStatus(status),new UpdateWrapper<MerchandiseSku>().in("spu_id",spuIds).eq("shop_id",shopId).eq("del_flag",EnumUtil.DelFlag.NO.getIndex()));
    }
	@Override
	@Transactional
	public void delBySpuIds(List<Long> spuIds, Long shopId) {
		//更新spu
		spuService.update(new MerchandiseSpu().setStatus(MdseEnum.MdseStatus.DOWN.getIndex()).setDelFlag(EnumUtil.DelFlag.YES.getIndex()),new UpdateWrapper<MerchandiseSpu>().in("spu_id",spuIds).eq("shop_id",shopId));
		//更新sku
		skuService.update(new MerchandiseSku().setStatus(MdseEnum.MdseStatus.DOWN.getIndex()).setDelFlag(EnumUtil.DelFlag.YES.getIndex()),new UpdateWrapper<MerchandiseSku>().in("spu_id",spuIds).eq("shop_id",shopId));
	}

	@Override
	public Map<Long, InnrIntegralMdseVo> findIntegralMdseMapBySkuIdsAndMLv(List<Long> skuIds, Integer mLv) {
		if(mLv==null){
			return new HashMap<>();
		}
		try {

			Result<Map<Long,InnrIntegralMdseVo>> result = innrIntegralMdseApi.innrIntegralMdsePost(skuIds,mLv);
			if(result.isSuccess()){
				return result.getData();
			}else {
				logger.info("innr根据skuId查询商品会员积分价失败---{}--{}",JSONObject.toJSONString(skuIds),mLv);
			}
		}catch (Exception e){
			logger.error("innr根据skuId查询商品会员积分价---{}--{}",JSONObject.toJSONString(skuIds),mLv, e);
		}
		return new HashMap<>();
	}

	@Override
	public int delSku(Integer skuId) {
		// 删sku
		if(skuService.removeById(skuId)) {
			// 删除规格
			merchandiseRuleValueMapper.deleteById(-1);
			if(merchandiseRuleValueMapper.deleteById(skuId) > 0) {
				// 删除规格对应关系
				if (merchandiseRuleValueRelaMapper.delete(new QueryWrapper<MerchandiseRuleValueRela>().eq("sku_id", skuId)) > 0)
					return 1;
			}
		}
		return 0;
	}

	@Override
	public int updateSpu(MerchandiseSpu merchandiseSpu) {
		List<MerchandisePictureSpu> list = merchandisePictureSpuMapper.selectList(new QueryWrapper<MerchandisePictureSpu>().eq("shopid", merchandiseSpu.getShopId()).eq("spu_id", merchandiseSpu.getSpuId()));

		MerchandisePictureSpu  merchandisePictureSpu = null;
		if(list != null && list.size() > 0) {
			merchandisePictureSpu = list.get(0);
			merchandisePictureSpu.setPath(merchandiseSpu.getSpuPicture());
			merchandisePictureSpuMapper.updateById(merchandisePictureSpu);

		} else {
			merchandisePictureSpu = new MerchandisePictureSpu();
			merchandisePictureSpu.setPath(merchandiseSpu.getSpuPicture());
			merchandisePictureSpu.setDelFlag(0);
			merchandisePictureSpu.setShopid(merchandiseSpu.getShopId());
			merchandisePictureSpu.setSpuId(merchandiseSpu.getSpuId());
			merchandisePictureSpu.setSort(0);
			merchandisePictureSpu.setType(1);

			merchandisePictureSpuMapper.insert(merchandisePictureSpu);
		}

		// 设置价格最低的sku显示顺序
		List<MerchandiseSku> list2 = merchandiseSkuMapper.selectList(new QueryWrapper<MerchandiseSku>()
				.eq("status", 1)
				.eq("shop_id", merchandiseSpu.getShopId())
				.eq("spu_id", merchandiseSpu.getSpuId()));

		if(list2 != null && list2.size() > 0) {
			MerchandiseSku merchandiseSku = list2.get(0);
			merchandiseSku.setSequence(merchandiseSpu.getSequence());
			merchandiseSkuMapper.updateById(merchandiseSku);
		}

		return merchandiseSpuMapper.updateById(merchandiseSpu);
	}

	@Override
	@Transactional
	public void upAllStatusByCategoryIdPost(Integer status, Long shopId, Long categoryId) {
        List<Long> spuIds=new ArrayList<>();
           IPage<MerchandiseSpu> pa= spuService.selectLeftJoinMany(shopId, categoryId);
           if(pa!=null && pa.getRecords().size()>0){
               for (int i = 0; i < pa.getRecords().size(); i++) {
                   spuIds.add(pa.getRecords().get(i).getSpuId());
               }
           }
		//更新spu
		spuService.update(new MerchandiseSpu().setStatus(status),new UpdateWrapper<MerchandiseSpu>().in("spu_id",spuIds).eq("shop_id",shopId));
		//更新sku
		skuService.update(new MerchandiseSku().setStatus(status),new UpdateWrapper<MerchandiseSku>().in("spu_id",spuIds).eq("shop_id",shopId).eq("del_flag",EnumUtil.DelFlag.NO.getIndex()));
	}

	@Override
    public List<MerchandiseSkuDto> findSkuDtoListByCondition(List<Long> skuIds) {
        List<MerchandiseSku> skuList = findSkuListByIds(skuIds);
        List<MerchandiseSkuDto> skuDtoList = new ArrayList<>();
        skuList.forEach(sku->{
            MerchandiseSkuDto skuDto = fullSkuDtoBySku(sku);
            skuDtoList.add(skuDto);
        });
        return skuDtoList;
    }

	@Override
	public void derBatchQuantity(List<MerchandiseStoceEnvelope> skuNums) throws Exception {
		List<MerchandiseStoceEnvelope> stockHandledList = new ArrayList<>();
		Long nowSkuId = null;
		try {
			if(skuNums!=null&&!skuNums.isEmpty()){
				for (MerchandiseStoceEnvelope merchandiseStock : skuNums) {
					nowSkuId = merchandiseStock.getSkuId();
					Long stock=null;
					stock = decrbySkuStockBySkuId(merchandiseStock.getSkuId(), merchandiseStock.getNum());
					if(stock==null){
						throw new Exception("库存更新失败");
					}
					stockHandledList.add(merchandiseStock);
				}
			}
		} catch (Exception e) {
			if(stockHandledList!=null&&!stockHandledList.isEmpty()){
				for (MerchandiseStoceEnvelope merchandiseStock : stockHandledList) {
					Long stock=null;
					try {
							stock = decrbySkuStockBySkuId(merchandiseStock.getSkuId(), -merchandiseStock.getNum());
						if(stock==null){
							throw new Exception("库存更新失败");
						}
					} catch (Exception e1) {
						// 如果归还库存异常可能需要查看日志手动处理
						logger.error("库存更新退还库存错误 ---"+merchandiseStock.getSkuId()+"---"+merchandiseStock.getSkuId()+"---"+merchandiseStock.getNum(), e1);
					}
				}
			}
			logger.error("库存更新异常 ---"+nowSkuId, e);
			throw e;
		}
	}

	private Long decrbySkuStockBySkuId(Long skuId, Integer addNum) throws Exception {
		if(skuId==null){
			throw new Exception("skuId为空");
		}
		if(addNum==null){
			throw new Exception("addNum库存值为空"+skuId);
		}
		Long stock = null;
		String key =  getStockKey(skuId);
		if (stockTemplate.hasKey(key)) {
			stock = stockTemplate.opsForValue().increment(key, -addNum.longValue());
		} else {
			findMdseSkuStockBySkuId(skuId);
			stock = stockTemplate.opsForValue().increment(key, -addNum.longValue());
		}
		if(stock<0){
			stock = stockTemplate.opsForValue().increment(key,addNum.longValue());
			throw new Exception("库存不足");
		}
		putMq(skuId,stock);
		return stock;
	}

	private void putMq(Long skuId, Long stock) throws Exception {
		if(stock==null){
			throw new Exception("stockNum库存值为空");
		}
		mdseStock.handler(skuId, stock.intValue());
	}

	@Override
	public Integer findMdseSkuStockBySkuId(Long skuId) {
		Integer stock = null;
		String key =  getStockKey(skuId);
		if (!stockTemplate.hasKey(key)){
			synchronized (skuId){
				if (!stockTemplate.hasKey(key)) {
					stock = skuService.getById(skuId).getQuantity();
					if(stock != null){
						stockTemplate.opsForValue().set(key,stock);
					}
				}
			}
		}
		stock = stockTemplate.opsForValue().get(key);
		return stock;
	}

	private String getStockKey(Long skuId) {
		return SKU_STOCK+skuId;
	}

	private List<MerchandiseSku> findSkuListByIds(List<Long> skuIds) {
        return (List<MerchandiseSku>) skuService.listByIds(skuIds);
    }

    private List<MerchandiseRuleValue> findRuleValueListBySkuId(Long skuId) {
		List<MerchandiseRuleValueRela> relas = ruleValueRelaService.list(new QueryWrapper<MerchandiseRuleValueRela>().eq("sku_id",skuId));
		if(relas!=null&&!relas.isEmpty()){
			return (List<MerchandiseRuleValue>) ruleValueService.listByIds(relas.stream().map(MerchandiseRuleValueRela::getValueId).collect(Collectors.toList()));
		}
		return null;
	}

	private IPage<MerchandiseSku> findSkuPageByCondition(MerchandiseCondition condition) {
		QueryWrapper<MerchandiseSku> wrapper = new QueryWrapper<>();
		if(condition.getCategoryId()!=null){
			wrapper.eq("main_category",condition.getCategoryId());
		}
		if(condition.getStatus()!=null){
			wrapper.eq("status",condition.getStatus());
		}
		if(condition.getDelFlag()!=null){
			wrapper.eq("del_flag",condition.getDelFlag());
		}
		if(StringUtils.isNotBlank(condition.getMdseName())){
			wrapper.like("merchandise_name","%"+condition.getMdseName()+"%");
		}
		if(condition.getShopId()!=null){
			wrapper.eq("shop_id",condition.getShopId());
		}
		wrapper.gt(condition.isHaveQuantity(),"quantity",0);
        wrapper.groupBy(condition.isGroupSpu(),"spu_id");
        wrapper.orderByAsc("sequence");

		return skuService.page(new Page<>(condition.getPageIndex(),condition.getPageSize()),wrapper);
	}

	private List<Long> findSkuIdBySpuId(Long spuId) {
	    return skuService.list(new QueryWrapper<MerchandiseSku>().eq("spu_id",spuId)
                .eq("status",MdseEnum.MdseStatus.UP.getIndex())
                .eq("del_flag",EnumUtil.DelFlag.NO.getIndex())).stream().map(MerchandiseSku::getSkuId).collect(Collectors.toList());
    }

    private void saveSkuDtos(List<MerchandiseSkuDto> skuDtoList) throws Exception {
		if(skuDtoList==null||skuDtoList.isEmpty()){
			throw  new Exception("没有要保存的sku信息");
		}
		List<MerchandiseSku> skuList = new ArrayList<>();
		skuDtoList.stream().filter(Objects::nonNull)
				.filter(dto->dto.getSku()!=null)
				//处理sku
				.forEach(dto->skuList.add(dto.getSku()));
		skuService.saveOrUpdateBatch(skuList);
		//图片
		List<MerchandisePictureSku> picList = new ArrayList<>();
		List<MerchandiseRuleValueRela> relas = new ArrayList<>();
		skuDtoList.stream().filter(Objects::nonNull)
				//处理图片
				.peek(dto->dto.getSkuPics()
						.forEach(pic->picList.add(pic.setShopid(dto.getSku().getShopId())
							.setSkuId(dto.getSku().getSkuId()))))
				//处理关联规格
				.forEach(dto-> {//先删除
					if(logger.isDebugEnabled()) {
						logger.debug(JSON.toJSONString(dto));
					}
					ruleValueRelaService.remove(new QueryWrapper<MerchandiseRuleValueRela>()
							.eq("shopid",dto.getSku().getShopId())
							.eq("sku_id",dto.getSku().getSkuId()));
					if(dto.getRuleValues() != null) {
						relas.addAll(dto.getRuleValues().stream().filter(Objects::nonNull)
								.map(ruleVaule -> {
									//处理sku名字
									dto.getSku().setMerchandiseName(dto.getSku().getMerchandiseName() + ruleVaule.getRuleValue());
									return new MerchandiseRuleValueRela().setValueId(ruleVaule.getId())
											.setShopid(dto.getSku().getShopId())
											.setSkuId(dto.getSku().getSkuId());
								})
								.collect(Collectors.toList()));
					}
				});


		//保存sku后skuid就存在了
		if(!picList.isEmpty()){
			skuPicService.saveOrUpdateBatch(picList);
		}
//        logger.info(JSON.toJSONString(relas));
        if(!relas.isEmpty()){
			skuService.saveOrUpdateBatch(skuList);
			ruleValueRelaService.saveOrUpdateBatch(relas);
		}
	}

	private List<MerchandiseSkuDto> findMdseSkuDtoBySpuId(Long spuId) {
		List<MerchandiseSkuDto> mdseSkuDtoList = new ArrayList<>();
		List<MerchandiseSku> mdseSkuList = skuService.list(new QueryWrapper<MerchandiseSku>().eq("spu_id",spuId).eq("del_flag",0));
		if(mdseSkuList==null||mdseSkuList.size()<=0){
			return null;
		}
		for (MerchandiseSku sku : mdseSkuList) {
			if(sku==null){
				continue;
			}
			MerchandiseSkuDto mdseSkuDto = new MerchandiseSkuDto();
			mdseSkuDto.setSku(sku);
			//查询sku商品对应规则
			List<MerchandiseRuleValueRela> ruleValueRela = ruleValueRelaService.list(new QueryWrapper<MerchandiseRuleValueRela>().eq("sku_id",sku.getSkuId()));
			Set<Long> ruleValueIds = ruleValueRela.stream().map(MerchandiseRuleValueRela::getValueId).collect(Collectors.toSet());
			if(ruleValueIds!=null&&!ruleValueIds.isEmpty()){
				List<MerchandiseRuleValue> ruleValues  = (List<MerchandiseRuleValue>) ruleValueService.listByIds(ruleValueIds);
				mdseSkuDto.setRuleValues(ruleValues.stream().filter(a->a.getIsUse()==0).collect(Collectors.toList()));
			}
			//查询图片
			List<MerchandisePictureSku> mdsePicSkuList = skuPicService.list(new QueryWrapper<MerchandisePictureSku>().eq("del_flag",0).eq("sku_id",sku.getSkuId()));
			mdseSkuDto.setSkuPics(mdsePicSkuList);
			mdseSkuDtoList.add(mdseSkuDto);
		}
		return mdseSkuDtoList;
	}
}
